<template>
  <div>
    <div style="margin-top: 20px;">
      <el-button plain @click="dialogVisible = true">
        <img src="../../assets/上传1.png" style="width: 20px; height: 20px; margin-right: 5px;">上传
      </el-button>
      <el-button plain @click="dialogVisibleCreate = true">
        <img src="../../assets/新建.png" style="width: 20px; height: 20px; margin-right: 5px;">新建
      </el-button>
    </div>

    <el-dialog v-model="dialogVisible"  width="40%" :before-close="handleClose" class="custom-dialog">
      <div class="upload-content">
        <!-- 上传文件标题 -->
        <div class="upload-title">上传文件</div>

        <!-- 只能上传指定格式的文件提示 -->
        <div class="upload-tip">很高兴为您服务，我们只能上传指定格式的文件哦~</div>

        <!-- 上传按钮 -->
        <el-upload :action="uploadFileUrl" :data="extraData" :before-upload="beforeFileUpload"
          :on-success="handleSuccess" :headers="customHeaders" class="custom-upload">
          <el-button type="primary" class="upload-btn">点击上传</el-button>
        </el-upload>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="dialogVisible = false" class="confirm-btn">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新建目录对话框 -->
    <el-dialog v-model="dialogVisibleCreate" title="新建目录" width="500px" :before-close="handleClose">
      <template #default>
        <!-- 输入框部分 -->
        <el-input v-model="folderName" placeholder="请输入新建目录名称"
          style="width: 100%; margin-bottom: 20px; font-size: 14px; padding: 8px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);" />
      </template>

      <!-- 底部按钮部分 -->
      <template #footer>
        <div class="dialog-footer" style="display: flex; justify-content: flex-end; gap: 15px;">
          <el-button @click="dialogVisibleCreate = false">关闭</el-button>
          <el-button type="primary" @click="createFolder">新建</el-button>
        </div>
      </template>
    </el-dialog>




    <!-- 表格内容 -->
    <div class="file-table">
      <!-- 搜索框 -->
      <div class="search">
        <el-input v-model="search" placeholder="搜索" style="width: 300px;cursor: pointer;"></el-input>
        <el-button plain @click="searchFile" style="margin-left: 10px;">
          <img src="../../assets/搜索.png" style="width: 20px; height: 20px; margin-right: 5px;">
        </el-button>
      </div>
      <br>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator=">">
        <el-breadcrumb-item v-for="(item, index) in currentPath" :key="index" @click="navigateTo(index)"
          class="breadcrumb-item">
          {{ item.name }}
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-table :data="files" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="文件名" width="300">
          <template #default="scope">
            <!-- 添加点击事件监听器到最外层的容器 -->
            <div class="file-name-container" @click="fileClickHandler(scope.row)">
              <span class="file-type">
                <el-icon>
                  <component :is="getIconComponent(scope.row.typeId)" />
                </el-icon>&nbsp;
              </span>
              <span class="file-name">{{ scope.row.fileName }}</span> <!-- 文件名 -->

              <!-- 图标组 -->
              <span class="icon-group" @mouseenter="showIconsRow = scope.$index" @mouseleave="showIconsRow = null"
                :class="{ 'icons-visible': showIconsRow === scope.$index }">
                <el-icon @click.stop="shareHandler(scope.row)" class="icon-spacing">
                  <Share />
                </el-icon>
                <el-icon @click.stop="downloadHandler(scope.row)" class="icon-spacing">
                  <Download />
                </el-icon>
                <el-icon @click.stop="deleteHandler(scope.row)" class="icon-spacing">
                  <Delete />
                </el-icon>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="200"></el-table-column>
        <el-table-column prop="fileSize" label="大小" width="100">
          <template #default="scope">
            {{ formatSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件: total必须是number -->
    <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="filteredTableData.total"
      :current-page="filteredTableData.current" :page-sizes="[1, 5, 10]" :page-size="filteredTableData.size"
      @size-change="pageSizeChange" @current-change="pageNumChange">
      <!-- 自定义分页文本 -->
      <template #total>
        共计 {{ filteredTableData.total }} 条
      </template>
      <template #sizes>
        每页显示
        <el-select v-model="filteredTableData.size" style="width: 80px;" @change="pageSizeChange">
          <el-option v-for="item in pageSizes" :key="item" :label="`${item} 条`" :value="item"></el-option>
        </el-select>
        条
      </template>
      <template #prev>
        上一页
      </template>
      <template #next>
        下一页
      </template>
      <template #jumper>
        跳转到第
        <el-input-number v-model="filteredTableData.current" :min="1"
          :max="Math.ceil(filteredTableData.total / filteredTableData.size)" size="mini"
          @change="pageNumChange"></el-input-number>
        页
      </template>
    </el-pagination>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享文件" width="400px">
      <el-form :model="shareForm">
        <el-form-item label="过期时间（天）">
          <el-input v-model="shareForm.expireTime" type="number" min="1" placeholder="请输入过期时间（天）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shareDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="generateShareLink">生成链接</el-button>
      </template>
    </el-dialog>

  </div>

</template>

<script setup lang="ts">
import { ref, onMounted, inject } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { FolderOpened, Folder, Document, VideoPlay, Picture, Headset } from '@element-plus/icons-vue';
import axios from "@/utils/request.js";

let $message = inject('$message');

// 从 localStorage 中获取 token 并解析 userId
const token = localStorage.getItem("token");
let userId = 0;

// 假设解析 token 的逻辑
if (token) {
  try {
    const parsedToken = JSON.parse(atob(token.split(".")[1])); // 假设 token 是 JWT 格式
    userId = parsedToken.userId || 0;
  } catch (error) {
    console.error("Token 解析失败:", error);
    userId = 1; // 如果解析失败，设置为 0 或其他默认值
  }
} else {
  userId = 2; // 假设没有 token，手动设置一个假 userId
}


//返回的数据
const filteredTableData = ref({
  total: 0,
  current: 1,
  size: 10,
})
//文件查询的数据
const formSearch = ref({
  pageSize: 10,
  pageNum: 1,
  fileId: 0,
  parentId: 0,
  title: '',
  author: ''
})

/*  分页功能 */
const pageSizeChange = function (newPageSize) {
  formSearch.value.pageSize = newPageSize
  getTableData()
}
const pageNumChange = function (newPageNum) {
  formSearch.value.pageNum = newPageNum
  getTableData()
}

//1.发送请求获取数据
const getTableData = async () => {
  //获取具体文件下的文件列表数据
  const res = await axios.get('/file/getlist', {
    params: {
      fileId: formSearch.value.fileId,
      parentId: formSearch.value.parentId,
      pageNum: formSearch.value.pageNum,
      pageSize: formSearch.value.pageSize
    }
  }).then(respose => {
    if (respose.data === null) {
      filteredTableData.value.current = 1;
      filteredTableData.value.total = 0;
      files.value = [];
      return;
    }
    //将查询中的records数据赋值给files（里面是一个个文件对象）
    files.value = respose.data.records;
    //将总的数据输出到filteredTableData,用于分页
    filteredTableData.value = respose.data;
    console.log(filteredTableData.value);
  }).catch(error => {
    console.log(error);
  });


}
// 判断是否是文件夹，是文件夹则进入文件夹，否则弹出提示框，该文件暂不支持预览
const fileClickHandler = (row) => {
  console.log(row);  // Add a log to inspect the row
  if (row.typeId === 1) { // typeId为1表示文件夹
    enterDirectory(row);
  } else {
    $message.warning('该文件暂不支持预览');
  }
};

// 页面大小选项
const pageSizes = [1, 5, 10];
// 面包屑路径数据

// 控制哪一行的图标应该显示
const showIconsRow = ref<number | null>(null);

// 定义当前路径数组
const currentPath = ref([
  { name: '根目录', path: '/', fileId: 0 },
]);

// 模拟进入下一级目录
const enterDirectory = (dir) => {
  currentPath.value.push({ name: dir.fileName, path: `${currentPath.value[currentPath.value.length - 1].path}${dir.fileName}/`, fileId: dir.fileId });
  formSearch.value.parentId = dir.fileId; // 假设fileId代表文件夹ID
  formSearch.value.fileId = dir.fileId;
  formSearch.value.pageNum = 1;
  formSearch.value.pageSize = 10;
  getTableData();
};

// 导航到指定层级
const navigateTo = (index) => {
  const targetDir = currentPath.value[index];
  currentPath.value.splice(index + 1); // 截断数组至指定索引
  formSearch.value.fileId = index === 0 ? 0 : targetDir.fileId; // 回到根目录或指定父级ID
  //重置分页
  formSearch.value.pageNum = 1;
  formSearch.value.pageSize = 10;
  getTableData();
};




// 上传弹框开关
const dialogVisible = ref(false);
// 上传文件地址
const uploadFileUrl = 'http://localhost:8080/file/upload';
// 自定义请求头
const customHeaders = {
  'token': localStorage.getItem('token')
};
// 上传弹框数据
const extraData = {
  //parentId绑定的是当前面包屑路径的最后一个文件夹的fileId
  parentId: currentPath.value[currentPath.value.length - 1].fileId
};

// 上传文件前的逻辑
const beforeFileUpload = (file) => {
  // 处理上传前的逻辑,判断文件类型是否符合要求
  const isAllowed = ['.jpg', '.jpeg', '.png', '.gif', '.mp4', '.mp3', '.zip', '.rar', '.txt', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'];
  const isAllowedType = isAllowed.some(type => file.name.endsWith(type));
  if (!isAllowedType) {
    ElMessage.error('只能上传指定格式的文件');
    return false;
  }
  return true;
}

// 上传成功后的逻辑
const handleSuccess = (response, file) => {
  // 处理上传成功后的逻辑,判断是否上传成功
  if (response.code === 200) {
    console.log(response.data);
    ElMessage.success('上传成功');
    // 刷新文件列表
    getTableData();
  } else {
    ElMessage.error('上传失败');
  }
};



// 新建弹框开关
const dialogVisibleCreate = ref(false);
// 新建文件夹名称
const folderName = ref('');
// 新建文件夹
const createFolder = () => {
  // 处理新建文件夹逻辑

  axios.post('/file/create', null, {
    params: {
      parentId: currentPath.value[currentPath.value.length - 1].fileId,
      folderName: folderName.value
    }
  }).then(response => {

    if (response.code === 200) {
      ElMessage.success('新建成功');
      // 刷新文件列表
      getTableData();
      dialogVisibleCreate.value = false;
    } else {
      ElMessage.error('新建失败');
    }
    // 关闭弹框
    dialogVisibleCreate.value = false;
  }).catch(err => {
    console.log(err);
  });
};



// 搜索框
const search = ref('');
// 搜索文件
const searchFile = () => {
  console.log(search.value); // 搜索框内容
  // 处理搜索逻辑
  axios.get('/file/search', {
    params: {
      fileName: search.value,
      parentId: currentPath.value[currentPath.value.length - 1].fileId,
      pageNum: 1,
      pageSize: 10
    }
  }).then(res => {
    console.log(res.data);
    if (res.data === null) {
      ElMessage.error('没有搜索到相关文件');
      return;
    }
    filteredTableData.value = res.data;
    files.value = res.data.records;
  }).catch(err => {
    console.log(err);
  });
  //清空搜索框
  search.value = '';
};


// 上传文件 关闭弹框
const handleClose = (done: () => void) => {
  done();
};

// 文件对象数据表格数据
const files = ref([]);

// 动态选择图标的函数
const getIconComponent = (type) => {
  switch (type) {
    case 1:
      return Folder; // 文件夹图标组件
    case 2:
      return Picture; // 图片图标组件
    case 3:
      return Document; // 文档图标组件
    case 4:
      return VideoPlay; // 视频图标组件
    case 5:
      return Headset; // 音乐图标组件
    case 6:
      return FolderOpened; // 压缩包图标组件
    default:
      return Folder; // 默认图标组件
  }
};

// 格式化文件大小的函数
const formatSize = (size) => {
  if (size === '-') return '-';

  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  let unitIndex = 0;

  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  // 保留两位小数
  return unitIndex === 0 ? `${Math.floor(size)} ${units[unitIndex]}` : `${size.toFixed(2)} ${units[unitIndex]}`;
};


// 数据和状态管理
const shareDialogVisible = ref(false);
const shareForm = ref({
  fileId: null,       // 由前端选中的文件ID填充
  expireTime: 7,      // 默认过期时间为 7 天
});
const shareLink = ref('');

// 这里添加 shareHandler 方法
const shareHandler = (file) => {
  // 打开分享对话框并设置文件ID
  shareForm.value.fileId = file.fileId;  // 文件ID从前端选中的文件获取
  shareDialogVisible.value = true;
};

// 调用后端生成分享链接
const generateShareLink = async () => {
  try {
    const response = await axios.get("/file/share", {
      params: {
        user_id: userId,                      // 当前登录用户的userId
        file_id: shareForm.value.fileId,      // 选中的文件ID
        expire_time: shareForm.value.expireTime, // 用户输入的过期时间
      },
    });

    console.log(response);

    if (response.code === 200) {  // 修改为 response.data.code
      shareLink.value = response.data;  // 生成的分享链接
      ElMessage.success("分享链接已生成");
    } else {
      ElMessage.error("生成分享链接失败");
    }
  } catch (error) {
    console.error("生成分享链接失败:", error);
    ElMessage.error("生成分享链接失败，请稍后重试");
  }
};


// const selectedFile = ref(null);


// 处理下载按钮点击事件
const handleDownload = (file) => {
  console.log('Download button clicked');
  // 如果没有选中任何文件，提示用户选择文件
  if (!file) {
    ElMessage.warning('请先选择一个文件！');
    return;
  }

  // 弹出确认框，确认是否下载
  ElMessageBox.confirm(`确定下载文件：${file.fileName}?`)
    .then(() => {
      // 用户确认下载，执行下载操作
      downloadHandler(file);
    })
    .catch(() => {
      ElMessage.info('已取消下载');
    });
};

const downloadHandler = (file) => {
  ElMessageBox.confirm(`确定下载文件：${file.fileName}?`).then(() => {
    axios.get('/file/download', {
      params: {
        fileId: file.fileId
      },
      responseType: 'blob'
    }).then(res => {
      let fileName = file.fileName;
      // 创建a标签并下载文件
      const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/octet-stream' }));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      // 释放 URL 对象
      window.URL.revokeObjectURL(url);

    }).catch(err => {
      console.error("下载失败:", err);
      ElMessage.error('下载文件失败，请稍后再试。');
    });
  }).catch(() => {
    ElMessage.info('已取消下载。');
  });
};


// 删除文件
const deleteHandler = (file) => {
  ElMessageBox.confirm(`确定删除文件：${file.fileName}?`).then(() => {
    // 处理删除逻辑
    axios.delete('/file/delete', {
      params: {
        fileId: file.fileId
      }
    }).then(res => {
      console.log(res.data);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        // 刷新文件列表
        getTableData();
      } else {
        ElMessage.error('删除失败');
      }
    }).catch(err => {
      console.error("删除失败:", err);
      ElMessage.error('删除文件失败，请稍后再试。');
    });
  }).catch(() => { });
};




onMounted(() => {
  getTableData();
});
</script>

<style scoped>
/* 整体文件列表容器 */
.file-table {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
  padding: 20px;
}

/* 头部区域样式 */
.header {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
}

/* 搜索框样式 */
.search {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search .el-input {
  width: 250px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search .el-button {
  margin-left: 10px;
  border-radius: 20px;
  background-color: #9ec3f3;
  color: white;
  padding: 6px 12px;
}

/* 面包屑导航 */
.el-breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
}

.el-breadcrumb-item {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
  transition: color 0.3s ease;
}

.el-breadcrumb-item:hover {
  color: #66b1ff;
}

/* 文件名列样式 */
.file-name-container {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-left: 10px;
}

.file-type {
  width: 40px;
}

.icon-spacing {
  margin-left: 12px;
  margin-right: 10px;
  color: #909399;
  transition: color 0.3s ease;
}

.icon-spacing:hover {
  color: #409eff;
}

.icon-group {
  display: none;
  justify-content: flex-start;
  align-items: center;
}

.icon-group .el-icon {
  margin-left: 12px;
}

.file-name-container:hover .icon-group {
  display: flex;
}

/* 分页组件样式 */
.el-pagination {
  margin-top: 20px;
  font-size: 14px;
}

.el-pagination .el-button {
  padding: 5px 10px;
  border-radius: 20px;
}

.el-select {
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 文件上传和新建文件夹按钮 */
.el-button {
  border-radius: 20px;
  padding: 8px 16px;
  margin-right: 12px;
  font-weight: 500;
}

.el-button:hover {
  background-color: #f0f9ff;
}

.el-dialog {
  border-radius: 10px;
  overflow: hidden;
}

.el-dialog .dialog-footer {
  text-align: right;
}

/* 文件列表中的图标和文件类型 */
.el-table-column .file-type img {
  width: 24px;
  height: 24px;
}

/* 图标显示逻辑 */
.icon-group {
  display: none;
}

.icon-group.icons-visible {
  display: inline-flex;
  justify-content: space-between;
  align-items: center;
  width: 100px;
}

.icon-group .el-icon {
  margin-left: 10px;
  cursor: pointer;
}

/* 图标显示：悬停文件名时显示操作图标 */
.file-name-container:hover .icon-group {
  display: flex;
}

/* 其他细节 */
.el-button[type="primary"] {
  background-color: #409eff;
  color: white;
}

.el-button[type="primary"]:hover {
  background-color: #66b1ff;
}

.el-table th {
  background-color: #f2f4f7;
  color: #606266;
  text-align: center;
}

.el-table .el-table-column {
  padding: 10px;
  text-align: center;
  font-size: 14px;
}

.el-dialog .el-dialog__body {
  padding: 20px;
}

/* 文件大小格式化 */
.file-size {
  font-weight: 500;
  color: #999;
}


/* 上传文件样式 */
/* 对话框样式 */
.custom-dialog .el-dialog__header {
  background-color: #409EFF;
  /* 设置头部背景颜色 */
  color: white;
  font-weight: bold;
  border-radius: 8px 8px 0 0;
}

.custom-dialog .el-dialog__body {
  padding: 20px;
}

/* 弹窗内容容器 */
.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
}

/* 上传文件标题 */
.upload-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 15px;
}

/* 上传文件提示文字 */
.upload-tip {
  font-size: 14px;
  color: #999;
  margin-bottom: 20px;
}

/* 上传按钮 */
.custom-upload .el-upload__tip {
  display: none;
  /* 隐藏默认的提示文字 */
}

.upload-btn {
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.upload-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

/* 底部按钮 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
}

.cancel-btn {
  border-color: #dcdfe6;
  color: #606266;
}

.confirm-btn {
  background-color: #409EFF;
  color: white;
}

.cancel-btn:hover,
.confirm-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}
</style>
